<template>
  <div class="audit-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">充值审核</h2>
      <p class="page-subtitle">审核用户充值申请</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">待审核</div>
            <div class="stat-value">{{ pendingCount }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon approved">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">已通过</div>
            <div class="stat-value">{{ approvedCount }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon rejected">
            <el-icon><Close /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">已拒绝</div>
            <div class="stat-value">{{ rejectedCount }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选和操作区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <div class="filter-left">
          <el-select v-model="statusFilter" placeholder="筛选状态" clearable @change="fetchRequests">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </div>
        <div class="filter-right">
          <el-button @click="fetchRequests" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 申请列表 -->
    <el-card class="requests-card" shadow="hover">
      <el-table 
        :data="requests" 
        stripe 
        v-loading="loading"
        empty-text="暂无充值申请"
      >
        <el-table-column prop="id" label="申请ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="full_name" label="真实姓名" width="120" />
        <el-table-column prop="amount" label="申请金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="payment_method" label="支付方式" width="120" />
        <el-table-column prop="request_time" label="申请时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.request_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)"
              :effect="row.status === 'pending' ? 'plain' : 'dark'"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="processed_time" label="处理时间" width="160">
          <template #default="{ row }">
            {{ row.processed_time ? formatDateTime(row.processed_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="admin_comment" label="备注" min-width="150">
          <template #default="{ row }">
            {{ row.admin_comment || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons" v-if="row.status === 'pending'">
              <el-button 
                type="success" 
                size="small" 
                @click="handleApprove(row)"
                :loading="processing === row.id"
              >
                通过
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleReject(row)"
                :loading="processing === row.id"
              >
                拒绝
              </el-button>
            </div>
            <span v-else class="processed-text">已处理</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="500px"
      @close="resetDialog"
    >
      <div class="dialog-content">
        <div class="request-info">
          <p><strong>用户：</strong>{{ currentRequest?.username }} ({{ currentRequest?.full_name }})</p>
          <p><strong>申请金额：</strong>¥{{ currentRequest?.amount }}</p>
          <p><strong>支付方式：</strong>{{ currentRequest?.payment_method }}</p>
          <p><strong>申请时间：</strong>{{ formatDateTime(currentRequest?.request_time) }}</p>
        </div>
        
        <el-form :model="auditForm" label-width="80px">
          <el-form-item label="备注">
            <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="3"
              :placeholder="auditForm.action === 'approve' ? '审核通过原因（可选）' : '拒绝原因'"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            :type="auditForm.action === 'approve' ? 'success' : 'danger'"
            @click="confirmAudit"
            :loading="processing"
          >
            确认{{ auditForm.action === 'approve' ? '通过' : '拒绝' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getRechargeRequestsApi, 
  processRechargeRequestApi 
} from '@/utils/api';
import {
  Clock,
  Check,
  Close,
  Refresh
} from '@element-plus/icons-vue';

// 响应式数据
const requests = ref([]);
const loading = ref(false);
const processing = ref(null);
const statusFilter = ref('');
const dialogVisible = ref(false);
const currentRequest = ref(null);
const auditForm = ref({
  action: '',
  comment: ''
});

// 获取管理员信息
const adminInfo = JSON.parse(localStorage.getItem('user'));

// 计算属性
const pendingCount = computed(() => 
  requests.value.filter(r => r.status === 'pending').length
);

const approvedCount = computed(() => 
  requests.value.filter(r => r.status === 'approved').length
);

const rejectedCount = computed(() => 
  requests.value.filter(r => r.status === 'rejected').length
);

const dialogTitle = computed(() => 
  auditForm.value.action === 'approve' ? '审核通过' : '审核拒绝'
);

// 获取充值申请列表
const fetchRequests = async () => {
  try {
    loading.value = true;
    const res = await getRechargeRequestsApi({ 
      status: statusFilter.value || null 
    });
    
    if (res.code === 200) {
      requests.value = res.data || [];
    } else {
      ElMessage.error(res.message || '获取申请列表失败');
    }
  } catch (error) {
    console.error('获取充值申请失败:', error);
    ElMessage.error('获取申请列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理通过申请
const handleApprove = (request) => {
  currentRequest.value = request;
  auditForm.value = {
    action: 'approve',
    comment: ''
  };
  dialogVisible.value = true;
};

// 处理拒绝申请
const handleReject = (request) => {
  currentRequest.value = request;
  auditForm.value = {
    action: 'reject',
    comment: ''
  };
  dialogVisible.value = true;
};

// 确认审核
const confirmAudit = async () => {
  if (auditForm.value.action === 'reject' && !auditForm.value.comment.trim()) {
    ElMessage.warning('拒绝申请时必须填写拒绝原因');
    return;
  }

  try {
    processing.value = currentRequest.value.id;
    
    const res = await processRechargeRequestApi({
      request_id: currentRequest.value.id,
      admin_id: adminInfo.user_id,
      status: auditForm.value.action === 'approve' ? 'approved' : 'rejected',
      admin_comment: auditForm.value.comment.trim() || null
    });

    if (res.code === 200) {
      ElMessage.success(res.message);
      dialogVisible.value = false;
      await fetchRequests();
    } else {
      ElMessage.error(res.message || '审核失败');
    }
  } catch (error) {
    console.error('审核失败:', error);
    ElMessage.error('审核失败，请重试');
  } finally {
    processing.value = null;
  }
};

// 重置对话框
const resetDialog = () => {
  currentRequest.value = null;
  auditForm.value = {
    action: '',
    comment: ''
  };
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  };
  return statusMap[status] || status;
};

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString('zh-CN');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchRequests();
});
</script>

<style lang="less" scoped>
.audit-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 20px;
  }

  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: white;

    &.pending {
      background: linear-gradient(135deg, #e6a23c 0%, #f56c6c 100%);
    }

    &.approved {
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    }

    &.rejected {
      background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
    }
  }

  .stat-info {
    flex: 1;

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
  border: none;

  :deep(.el-card__body) {
    padding: 16px 20px;
  }
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .filter-left {
    display: flex;
    gap: 16px;
    align-items: center;
  }

  .filter-right {
    display: flex;
    gap: 12px;
  }
}

.requests-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 0;
  }

  .amount-text {
    font-weight: 600;
    color: #f56c6c;
  }

  .action-buttons {
    display: flex;
    gap: 8px;
  }

  .processed-text {
    color: #909399;
    font-size: 14px;
  }
}

.dialog-content {
  .request-info {
    background: #f5f7fa;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 20px;

    p {
      margin: 8px 0;
      font-size: 14px;

      strong {
        color: #303133;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .audit-page {
    padding: 16px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .filter-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .action-buttons {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
